package com.sopaths.web.controller;

import java.io.IOException;

import javax.inject.Inject;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import com.sopaths.connect.SopathsConnect;
import com.sopaths.contract.domain.LoginType;
import com.sopaths.contract.domain.User;
import com.sopaths.utility.web.WebUtil;

@Controller
@RequestMapping("/connect/login")
public class ConnectLoginController {

	@Inject
	private SopathsConnect connectService;

	@RequestMapping("/{type}")
	public void login(@PathVariable("type") LoginType loginType, HttpServletResponse response) throws IOException {
		String authorizeURL = connectService.getAuthorizeURL(loginType);
		response.sendRedirect(authorizeURL);
	}

	@RequestMapping(value = "/callback/{type}")
	public void authorizationCallback(@PathVariable("type") LoginType loginType, HttpSession session, HttpServletResponse response) throws IOException {
		User user = connectService.getUserInfo(loginType);
		session.setAttribute("user", user);

		String redirectURI = WebUtil.getLastPageURI();
		response.sendRedirect(redirectURI);
	}

	public void setConnectService(SopathsConnect connectService) {
		this.connectService = connectService;
	}
}
